package com.htfyun.ft.fragment.factory;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;

import com.htfyun.ft.BaseActivity;
import com.htfyun.ft.R;
import com.htfyun.ft.common.SettingsUtils;
import com.htfyun.ft.fragment.factory.FactoryBaseFragment;
import com.htfyun.ft.utils.DebugLog;

import java.util.Locale;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatTextView;

public class FragmentTP extends FactoryBaseFragment {

    private RelativeLayout parentContainer;

    private boolean mViewItemsCreated = false;

    private Rect rectTemp = new Rect();
    private boolean isAllItemGone = true;

    public float itemViewWidth;
    public float itemViewHeight;

    @Override
    protected int getLayoutRes() {
        return R.layout.fragment_factory_tp;
    }

    @Override
    protected void onInitView(@Nullable Bundle savedInstanceState) {

        super.onInitView(savedInstanceState);
        parentContainer = (RelativeLayout) findViewById(R.id.touch_draw_root_layout);

        itemViewWidth = getResources().getDimension(R.dimen.touch_draw_item_view_size);
        itemViewHeight = getResources().getDimension(R.dimen.touch_draw_item_view_size);

        DebugLog.e("onInitView this " + this);

    }

    @Override
    protected void onVisible() {
        super.onVisible();
        SettingsUtils.setTouchShowEnabled(true);
        createAllViewItems();


        DebugLog.e("hhhh onVisible = " + this);

    }

    @Override
    protected void onInvisible() {
        super.onInvisible();
        SettingsUtils.setTouchShowEnabled(false);
        removeAllViewItems();
    }



    private void createAllViewItems(){

        if( mViewItemsCreated ) return ;
        mViewItemsCreated = true;

        CreateViewItems(mContext, parentContainer);
    }

    private void removeAllViewItems() {
        removeAllViewItems(parentContainer);
    }

    private void removeAllViewItems(RelativeLayout parent) {
        if( !mViewItemsCreated ) return ;
        mViewItemsCreated = false;
        parent.removeAllViews();

    }

    private void CreateViewItems(Context context, RelativeLayout parent) {

        if (getActivity() == null) {
            return;
        }

        parent.removeAllViews();

        isAllItemGone = false;

        int w = parent.getWidth();
        int h = parent.getHeight();

        if (w == 0 || h == 0) {
            DisplayMetrics dm = new DisplayMetrics();
            Display display = getActivity().getWindowManager().getDefaultDisplay();

            display.getMetrics(dm);
            w = dm.widthPixels;
            h = dm.heightPixels;
        }

        float viewW = itemViewWidth;
        float viewH = itemViewHeight;
        int itemViewCountHorizontal = (int)(w / itemViewWidth);
        int itemViewCountVertical = (int)(h / itemViewHeight);
        float deltaW = 1.0f * w % itemViewWidth;
        float deltaH = 1.0f * h % itemViewHeight;

        viewW += deltaW / itemViewCountHorizontal;
        viewH += deltaH / itemViewCountVertical;

        int index = 0;

        for (int i = 0; i < itemViewCountVertical; i++) {

            if (i == 0 || i == (itemViewCountVertical / 2) || i == (itemViewCountVertical - 1)) {

                for (int j = 0; j < itemViewCountHorizontal; j++) {

                    TouchViewItem v = new TouchViewItem(context,
                            j * viewW, i * viewH,
                            (int) viewW, (int) viewH, index++);
                    parent.addView(v);

                }
            } else {

                for (int j = 0; j < 3; j++) {

                    float x = 0;
                    if (j == 1) {
                        x = (j * (itemViewCountHorizontal / 2.0f)) * viewW;

                    } else if (j == 2) {
                        x = ((itemViewCountHorizontal - 1)) * viewW;
                    }

                    TouchViewItem v = new TouchViewItem(context,
                            x, i * viewH,
                            (int) viewW, (int) viewH, index++);

                    parent.addView(v);
                }
            }
        }

    }

    private void tpTestPassed() {

        getHandler().postDelayed(new Runnable() {
            @Override
            public void run() {
                finishMeWithPassed(true);

            }
        }, 200);


    }

    private void checkTouchView(int x , int y){

        boolean allGone = true;
        int count = parentContainer.getChildCount();

        for (int i = 0; i < count; i ++) {

            View item = parentContainer.getChildAt(i);

            if (item.getVisibility() != View.VISIBLE) {
                continue;
            }

            item.getHitRect(rectTemp);
            if (rectTemp.contains(x, y) && item.getVisibility() != View.GONE) {
                item.setVisibility(View.GONE);
            }

            if (item.getVisibility() == View.VISIBLE) {
                allGone = false;
            }
        }

        if (allGone) {
            DebugLog.e("tp test items are all gone");
            isAllItemGone = true;
        }

    }

    @Override
    public void dispatchTouchEvent(MotionEvent event) {
        int x,y;
        x = (int) event.getX();
        y = (int) event.getY();

        if (event.getPointerCount() != 1) {
            return;
        }

        if (!isAllItemGone) {

            checkTouchView(x, y);

        } else {

            switch (event.getAction() & MotionEvent.ACTION_MASK) {
                case MotionEvent.ACTION_UP:
                case MotionEvent.ACTION_CANCEL:
                    tpTestPassed();
                    break;
            }
        }
    }


    // Button
    public class TouchViewItem extends AppCompatTextView {
        public int mIndex;

        private void init(int index ){
            mIndex = index;
            this.setText(String.format(Locale.getDefault(), "%d", index));
//            this.setTextSize((float)20.0);
            this.setTextColor(Color.BLACK);
            this.setGravity(Gravity.CENTER);
            this.setClickable(false);
            this.setFocusable(false);

            this.setBackgroundResource(R.drawable.textview_bg);
        }

        public TouchViewItem(Context context,float x, float y, int w , int h , int index ) {
            super(context);
//            WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
            this.setX(x);
            this.setY(y);
            this.setMinimumHeight(h);
            this.setMinimumWidth(w);
            init(index);
        }


        @Override
        public boolean performClick() {
            return super.performClick();
        }
    }

}
